package com.liuxinlong.api;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liuxinlong.common.AosException;
import com.liuxinlong.enums.ReturnCodes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 三色管理服务器api
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年12月13日
 */
@Service
@Slf4j
public class ThreeColorService implements ThreeColorInterface {

    public final static String LOGIN_URL_COLOR = "http://172.30.105.174:8011/DW/LdapLogin";

    public final static String USER_NAME_COLOR = "fule";

    public final static String PASSWORD_COLOR = "2777398b-e457-429c-8a53-c5a9eec16e97";

    public final static String CLIENT_COLOR = "dw_excel";

    public final static String LOGIN_TYPE_COLOR = "app";

    public final static String TARGET_URL_COLOR = "http://172.30.105.174:8011/Fine/ExecSqlTemplate";

    public final static String TEMPLATE_ID_COLOR = "color3_ecn_state";



    public final static String LOGIN_URL_PDF = "https://imstest.aosmith.cn:8443/gateway/dw2/DW/LdapLogin";

    public final static String USER_NAME_PDF = "rd_quality";

    public final static String PASSWORD_PDF = "d138dd92-0136-44e9-965f-e08d1bab7d8a";

    public final static String CLIENT_PDF = "system";

    public final static String LOGIN_TYPE_PDF = "app";

    public final static String TARGET_URL_PDF = "https://imstest.aosmith.cn:8443/gateway/dw2/Fine/ExecSqlTemplate";

    public final static String TEMPLATE_ID_PDF = "rd_quality_pdf_info";

    /**
     * 获取 token
     *
     * @return token
     */
    private String getColorToken() {
        StringBuffer buffer = new StringBuffer();
        String token = null;
        try {
            URL url = new URL(LOGIN_URL_COLOR);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            Map<String, Object> param = new HashMap<>();
            param.put("username", USER_NAME_COLOR);
            param.put("password", PASSWORD_COLOR);
            param.put("client", CLIENT_COLOR);
            param.put("login_type", LOGIN_TYPE_COLOR);
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            JSONObject res = JSONUtil.parseObj(buffer);
            token = (String) res.get("msg");

            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "获取 Token失败");
        } finally {

        }
        return token;
    }

    @Override
    public void pushAllStatusData() {

    }

    @Override
    public void pushIncrementalStatusData() {
        String token = getColorToken();
        HttpURLConnection httpUrlConn = null;
        StringBuffer buffer = new StringBuffer();
        String connectStatus;
        String msg;
        try {

            URL url = new URL(TARGET_URL_COLOR);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setRequestProperty("certificate", token);
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            List<String> dataList = new ArrayList<>();
            Map<String, Object> param = new HashMap<>();
            param.put("templateId", TEMPLATE_ID_COLOR);
            param.put("data", dataList.toString());
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            JSONObject res = JSONUtil.parseObj(buffer);
            connectStatus = (String) res.get("status");
            msg = (String) res.get("msg");

            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "连接失败");
        } finally {

        }
        System.out.println("msg: " + msg);
        if (StringUtils.equals(connectStatus, "success")) {
            System.out.println("msg: " + msg);
        } else {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "数据传输失败： "+msg);
        }
    }

    /**
     * 获取 token
     *
     * @return token
     */
    private String getPdfToken() {
        StringBuffer buffer = new StringBuffer();
        String token = null;
        try {
            URL url = new URL(LOGIN_URL_PDF);
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            Map<String, Object> param = new HashMap<>();
            param.put("username", USER_NAME_PDF);
            param.put("password", PASSWORD_PDF);
            param.put("client", CLIENT_PDF);
            param.put("login_type", LOGIN_TYPE_PDF);
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            JSONObject res = JSONUtil.parseObj(buffer);
            token = (String) res.get("msg");

            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "获取 Token失败");
        } finally {

        }
        return token;
    }

    @Override
    public void pushAllFileData(List<Map<String,String>> fileDataList) {

    }

    @Override
    public void pushIncrementalFileData(List<Map<String,String>> fileDataList) {
        String token = getPdfToken();
        System.out.println(token);
        HttpURLConnection httpUrlConn = null;
        StringBuffer buffer = new StringBuffer();
        String connectStatus;
        String msg;
        try {
            URL url = new URL(TARGET_URL_PDF);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
            httpUrlConn.setRequestProperty("certificate", token);
            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            Map<String, Object> param = new HashMap<>();
            param.put("templateId", TEMPLATE_ID_PDF);
            param.put("data", JSONUtil.toJsonStr(fileDataList));

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSONUtil.toJsonStr(param));
            System.out.println(JSONUtil.toJsonStr(param));
            osw.flush();
            osw.close();

            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            JSONObject res = JSONUtil.parseObj(buffer);
            connectStatus = (String) res.get("status");
            msg = (String) res.get("msg");

            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "连接失败");
        } finally {

        }
        System.out.println("msg: " + msg);
        if (StringUtils.equals(connectStatus, "success")) {
            System.out.println("msg: " + msg);
        } else {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "数据传输失败： "+msg);
        }
    }
}
